package main;

import script.Script;
import ui.Window;
import define.Common;
import define.Config;
import excelBase.ExcelFile;

public class ErrorHandler 
{
	private static boolean m_isErrorExists = false;
	public static Script m_errorScript = null;
	public static ExcelFile m_errorExcel = null;
	private static int m_errorCode = 0;
	
	public ErrorHandler(ErrorException e)
	{
		m_isErrorExists = true;
		m_errorCode = e.getErrorId();
		String error = e.getMessage();
		String pos = "";
		if(e.getPosition() != Config.NO_POSITION)
		{
			try 
			{
				pos = getPositionString(e.getPosition());
			} 
			catch(Exception e2)
			{
				pos = "     can't locate error position";
			}
		}
		error += pos;
		if(Common.m_hasUI)
		{
			Window.m_instance.addText(error);
		}
		else 
		{
			System.out.println(error);
		}
	}
	
	public static boolean isErrorExists()
	{
		return m_isErrorExists;
	}
	
	public static void reset()
	{
		m_isErrorExists = true;
	}
	
	public static int getErrorCode()
	{
		return m_errorCode;
	}
	
	private String getPositionString(int position) throws Exception
	{
		int start = m_errorScript.getRealPosition(position);
		int end = position + Config.ERROR_STRING_LEN;
		int[] tempArray = m_errorScript.readFile();
		if(end >= tempArray.length)
		{
			end = tempArray.length - 1;
		}
		int line = 1;
		int lineEnd = -1;
		for(int i = 0; i < start; ++i)
		{
			if(tempArray[i] == '\r')
			{
				++line;
				if(i < tempArray.length - 1 && tempArray[i + 1] == '\n')
				{
					++i;
				}
				lineEnd = i;
			}
			else if(tempArray[i] == '\n')
			{
				++line;
				lineEnd = i;
			}
		}
		lineEnd = start - lineEnd;
		String error = "-- ";
		for(int i = start; i <= end; ++i)
		{
			error += (char)tempArray[i];
		}
		error += " --";
		return "   line:" + line + ", " + lineEnd + ": " + error;
	}
}
